package com.lu.barcode

import android.graphics.Bitmap
import android.util.Log
import com.google.android.gms.tasks.Task
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage

/**
 *author: luqihua
 *date:2023/3/30
 *description:
 **/
object ScannerAnalyser {
    private const val TAG = "ScannerHelper"
    fun scanning(
        inputImage: InputImage,
        successListener: (barcode: Barcode) -> Unit,
        failureListener: ((Exception) -> Unit)? = null,
        completeListener: (() -> Unit)? = null,
    ): Task<List<Barcode>> {
        val options = BarcodeScannerOptions.Builder()
            .setBarcodeFormats(
                Barcode.FORMAT_QR_CODE,
                Barcode.FORMAT_AZTEC)
            .build()

        val scanner = BarcodeScanning.getClient(options)
        return scanner.process(inputImage)
            .addOnSuccessListener { barcodes ->
                Log.d(TAG, "scanBarcodes : barcodes = ${barcodes.size}")
                barcodes.firstOrNull()?.let(successListener)
            }
            .addOnFailureListener {
                Log.e(TAG, "scanBarcodes : ", it)
                failureListener?.invoke(it)
            }
            .addOnCompleteListener {
                Log.d(TAG, "scanBarcodes : complete")
                scanner.close()
                completeListener?.invoke()
            }
    }


    fun scanning(
        bitmap: Bitmap,
        successListener: (barcode: Barcode) -> Unit,
        failureListener: ((Exception) -> Unit)? = null,
        completeListener: (() -> Unit)? = null,
    ): Task<List<Barcode>> {
        val inputImage = InputImage.fromBitmap(bitmap, 0)
        return scanning(inputImage, successListener, failureListener, completeListener)
    }
}